package com.yimi.yinhepda.base;

import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.os.StrictMode;
import android.support.multidex.MultiDex;
import android.text.TextUtils;

import com.alibaba.android.arouter.launcher.ARouter;
import com.baidu.mobstat.StatService;
import com.google.gson.Gson;
import com.squareup.leakcanary.LeakCanary;
import com.tencent.bugly.crashreport.CrashReport;
import com.uce.pda.MyAppLication;
import com.yimi.yinhepda.BuildConfig;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.yimi.yinhepda.utils.CrashHandler;
import com.pda.uce.commom.util.LogUtil;
import com.pda.ym.utils.SharedPreferUtil;
import com.pda.ym.utils.StringUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.cookie.CookieJarImpl;
import com.zhy.http.okhttp.cookie.store.PersistentCookieStore;
import com.zhy.http.okhttp.https.HttpsUtils;
import com.zhy.http.okhttp.log.LoggerInterceptor;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * The class <code>BaseApplication</code>
 *
 * @author qianlx
 */
public class BaseApplication extends MyAppLication {
    private static final String TAG = BaseApplication.class.getName();
    public static BaseApplication mInstance;
    private static Context context;
    private static Gson gson;

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mInstance = this;
        context = getApplicationContext();
        gson = new Gson();

        CrashHandler handler = CrashHandler.getInstance();
        handler.init(mInstance);

        initOkHttpUtil();
        initBugly();

        initRouter(this);

//        initLeakCanary();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            // android 7.0系统解决拍照的问题
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
            builder.detectFileUriExposure();
        }

        //百度统计初始化
        StatService.start(this);
        //发布时关闭
        StatService.setDebugOn(false);
    }

    private void initRouter(Application application) {
        if (BuildConfig.DEBUG) {
            ARouter.openLog();     // 打印日志
            ARouter.openDebug();   // 开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
        }
        ARouter.init(application);
    }


    private void initLeakCanary(){
        if (LeakCanary.isInAnalyzerProcess(this)) {//1
            // This process is dedicated to LeakCanary for heap analysis.
            // You should not init your app in this process.
            return;
        }
        LeakCanary.install(this);
    }

    /**
     * 初始化OkHttpUtil的配置
     */
    private void initOkHttpUtil() {
        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);
        //cookie持久化存储，如果cookie不过期，则一直有效
        CookieJarImpl cookieJar = new CookieJarImpl(new PersistentCookieStore(getApplicationContext()));
        OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new LoggerInterceptor("TAG"))
                .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request;
                        Request.Builder builder = chain.request().newBuilder();
                        builder.addHeader("versionName", BuildConfig.VERSION_NAME);
                        builder.addHeader("versionCode", BuildConfig.VERSION_CODE + "");
                        builder.addHeader("os", android.os.Build.VERSION.RELEASE);
                        builder.addHeader("from", "PDA");
                        builder.addHeader("model", android.os.Build.MODEL);
                        //登录状态的Cookie
                        builder.addHeader("cookie", SharedPreferUtil.getInstance().getValue(Common.COOKIE)
                                + ";CompCode=" + SharedPreferUtil.getInstance().getCompanyCode()
                                + ";DeptCode=" + SharedPreferUtil.getInstance().getValue(Common.DEPT_CODE)
                                + ";OrgCode=" + SharedPreferUtil.getInstance().getValue(Common.DEPT_CODE)
                                + ";UserCode=" + SharedPreferUtil.getInstance().getValue(Common.USER_CODE)
                                + ";staging=1");

                        String url = chain.request().url().toString();
                        if (url.contains(Constants.LOGIN_URL)) {
                            //登录验证码 根据该值，取服务端的验证码，来校验
                            String vcode = SharedPreferUtil.getInstance().getValue(Common.VCODE);
                            if (!StringUtils.isEmpty(vcode)) {
                                builder.addHeader("cookie", SharedPreferUtil.getInstance().getValue(Common.VCODE) + ";path=/");
                            }
                        }
                        request = builder.build();
                        Response response = chain.proceed(request);
                        LogUtil.e("请求头：" + request.headers().toString());
                        return response;
                    }
                })
                .connectTimeout(50L, TimeUnit.SECONDS)
                .readTimeout(50L, TimeUnit.SECONDS)
                //其他配置
//                .cookieJar(cookieJar)
                .build();

        OkHttpUtils.initClient(okHttpClient);
    }

    /**
     * 初始化腾讯bugly
     * <p>
     * 增加了进程的上报，给服务器判断
     * <p>
     * CrashReport.initCrashReport的第二个参数"5147e882b9"是AppId
     * 第三个参数表示是否调试状态，true调试，false发布
     */
    public void initBugly() {

        Context context = getApplicationContext();
        // 获取当前包名
        String packageName = context.getPackageName();
        // 获取当前进程名
        String processName = getProcessName(android.os.Process.myPid());
        // 设置是否为上报进程
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
        strategy.setUploadProcess(processName == null || processName.equals(packageName));
        CrashReport.putUserData(context, "userCode", SharedPreferUtil.getInstance().getValue(Common.USER_CODE));
        CrashReport.putUserData(context, "userName", SharedPreferUtil.getInstance().getValue(Common.USER_NAME));
        CrashReport.putUserData(context, "phone", SharedPreferUtil.getInstance().getValue(Common.USER_PHONE));
        CrashReport.putUserData(context, "deptCode", SharedPreferUtil.getInstance().getDeptCode());
        CrashReport.putUserData(context, "deptName", SharedPreferUtil.getInstance().getValue(Common.DEPT_NAME));
        // 初始化Bugly
        if (BuildConfig.DEBUG) {
            CrashReport.initCrashReport(context, Constants.BUGLY_APP_ID, true, strategy);
        } else {
            CrashReport.initCrashReport(context, Constants.BUGLY_APP_ID, false, strategy);
        }
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }

    public void exit() {
        android.os.Process.killProcess(android.os.Process.myPid());
        //System.exit(0);

    }

    /**
     * 获取上下文
     */
    public static Context getContext() {
        if (context == null) {
            context = getInstance().getApplicationContext();
        }
        return context;
    }

    public static BaseApplication getInstance() {
        if (mInstance == null) {
            synchronized (BaseApplication.class) {
                if (mInstance == null) {
                    mInstance = new BaseApplication();
                }
            }
        }
        return mInstance;
    }

    public static Gson getGson() {
        return gson;
    }
}
